// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

var UnitTools = require('UnitTools')
var CreatorHelper = require('CreatorHelper')
var Config = require('Config')
var ClickManager = require('ClickManager')
var NetworkManager = require('NetworkManager')
var UserManager = require('UserManager')
var TableManager = require('TableManager')
var AudioManager = require('AudioManager')

cc.Class({
    extends: cc.Component,

    properties: {
        union: cc.Node,
        loading: cc.Node,
        loadingTxt: cc.Label,

        notice: cc.Label,
        unreadEmail: cc.Node,

        token: null,
        frameCount: 0,

        keyboard: cc.Node,
        roomIdLabel: cc.Label,
        roomIdTempString: '',

        alertModel: cc.Prefab, // 提示弹出框
        exitBtn: cc.Node,

        inviteNode1: cc.Node,
        inviteNode2: cc.Node
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.token = cc.sys.localStorage.getItem('__TOKEN__')
        this.pnode = this.node
        this.isGame = 0
        this.reconntionStatus = false

        // 加载联盟
        ClickManager.onClick(this.union, this, (arg) => {
            this.loadUnion()
        })

        CreatorHelper.loadPrefab('prefabs/Bgm', (node) => {
            this.pnode.addChild(node)
            node.getComponent('Bgm')._play()
        })

        // 退出游戏
        CreatorHelper.setNodeClickEvent(this.exitBtn, () => {
            cc.director.end()
            window.close()
        })

        // 商城
        var shopNode = cc.find('bg/footer/layout/shop', this.node)
        var shopNode2 = cc.find('bg/footer/layout/shop/shop_2', this.node)
        CreatorHelper.setNodeClickEvent(shopNode, () => {
            CreatorHelper.loadPrefab('prefabs/model/modelShop', (node) => {
                this.node.addChild(node)
            })
        })
        CreatorHelper.setNodeClickEvent(shopNode2, () => {
            CreatorHelper.loadPrefab('prefabs/model/modelShop', (node) => {
                this.node.addChild(node)
            })
        })

        CreatorHelper.setNodeClickEvent(this.inviteNode1, () => {
            TableManager.alertModel('维护中')
        })

        CreatorHelper.setNodeClickEvent(this.inviteNode1, () => {
            TableManager.alertModel('维护中')
        })

        this.keyboardInput()
    },

    start () {
        this.getHallData()
    },

    onEnable () {
        NetworkManager.updateUserInfo()
    },

    // 键盘输入
    keyboardInput () {
        let children = this.keyboard.children

        for (let i in children) {
            children[i].i = i
            ClickManager.onClick(children[i], children[i], () => {
                let idx = parseInt(children[i].i)
                if (idx < 9 || idx === 10) {
                    if (this.roomIdTempString.length >= 6) {
                        return false
                    }
                    if (idx === 10) idx = -1
                    this.roomIdTempString += ''+(idx+1)
                    this.roomIdLabel.string = this.roomIdTempString
                }

                // 确定
                if (idx === 9) {
                    if (this.roomIdTempString.length != 6) {
                        ClickManager.alertModel(this.alertModel, '房间id输入错误')
                        return false
                    }
                    this.linkTableServer()
                }

                // 删除
                if (idx === 11 && this.roomIdTempString.length > 0) {
                    this.roomIdTempString = this.roomIdTempString.slice(0, this.roomIdTempString.length-1)
                    this.roomIdLabel.string = this.roomIdTempString
                }
            })
        }
    },

    // 加入牌桌
    joinTable () {
        ClickManager.loading(this.pnode, '加入游戏牌桌中..')
        NetworkManager.onConnectedToGame((gameService) => {
            gameService.proxy.joinGameTable(this.token, this.roomIdLabel.string, (data) => {
                cc.log('加入游戏牌桌:', data)
                if ((data.ok && data.code === 200) || data.code === 201) {
                    UserManager.tid = data.tid

                    ClickManager.loading(this.pnode, '加入游戏牌桌成功...')
                    cc.director.preloadScene('table',  this.onProgress.bind(this), () => {
                        cc.log('加入牌桌场景')
                        if (!this.tableScene) {
                            ClickManager.rmLoading(this.pnode)
                            cc.director.loadScene('table')
                            this.tableScene = true
                        }
                    })
                } else if (data.ok && data.code === 0) {
                    ClickManager.rmLoading(this.pnode)
                    ClickManager.alertModel(this.alertModel, data.msg)
                } else if (!data.ok) {
                    ClickManager.rmLoading(this.pnode)
                    NetworkManager.onCloseFormGame()
                }
            })
        })
    },

    // 连接牌桌服务器
    linkTableServer () {
        ClickManager.loading(this.pnode, '连接游戏服务器中...')
        if (!NetworkManager.gGameServerIsLogin) {
            NetworkManager.connectAndAuthToGame()
        }
        NetworkManager.onConnectedToGame(() => {
            var loginData = UserManager.loginToGameData
            cc.log('连接游戏服务器:', loginData)
            if (loginData.isInGame) {
                // 登录成功，加入牌桌
                ClickManager.loading(this.pnode, '连接游戏服务器成功...')
                this.joinTable()
            } else {
                // 不在游戏服务器，登录失败
                NetworkManager.clearGameService()
                ClickManager.rmLoading(this.pnode)
                ClickManager.alertModel(this.alertModel, '连接游戏服务器失败')
            }
        })
    },

    // 获取大厅数据
    getHallData () {
        try {
            // 获取大厅数据
            NetworkManager.onConnectedToHall( (hallService) => {
                hallService.proxy.getHallConfig(this.token, (data) => {
                    if (data.code === 200 && data.ok) {
                        let datas = JSON.parse(data.datas)

                        this.notice.string = datas.notice
                        if (parseInt(datas.unreadEmail) > 0) {
                            this.unreadEmail.active = true
                        } else {
                            this.unreadEmail.active = false
                        }
                        this.isGame = datas.isGame
                        this.gameReconntion()
                    }
                })
            })
        } catch (err) {
            console.log('异常处理，待处理:', err)
            // cc.director.loadScene('login')
        }
    },

    // 游戏重连
    gameReconntion () {
        if (!this.reconntionStatus && this.isGame !== 0) {
            this.reconntionStatus = true
            CreatorHelper.loadPrefab('prefabs/IsGameing', (node) => {
                this.pnode.addChild(node)
                this.linkTableServer()
            })
        }
    },

    // 加载联盟
    loadUnion () {
        // 大厅场景预加载
        this.loading.active = true
        cc.director.preloadScene('union',  this.onProgress.bind(this), () => {
            this.loading.active = false
            cc.director.loadScene('union')
        })
    },

    // 加载进度
    onProgress (com, total, item) {
        if (total < 10) {
            total = this.initTotal
        }

        let progress = com / total
        progress = isNaN(progress) ? 0 : progress

        this.loadingTxt.string = '静态资源加载中('+ (progress*100).toFixed(2) +'%)...'
    },

    update (dt) {
        this.frameCount++
        if (this.frameCount % 200 === 0) {
            NetworkManager.updateUserInfo()
            this.getHallData()
        }
    },
});
